import { TaskExecution, TaskHistory } from "../components/HomeDashboard";
import { useTaskContext } from '../contexts/TaskContext';
import { useTaskHistoryContext } from '../contexts/TaskHistoryContext';
import { Task, ExecutionRecord } from '../contexts/types';
import { ExecutionRecord as ComponentExecutionRecord } from '../components/HomeDashboard/types';

// 创建类型转换函数
const adaptTaskToComponentFormat = (tasks: Task[]): Record<string, any[]> => {
  // 按分类对任务模板进行分组
  return tasks.reduce((acc: { [key: string]: any[] }, task: Task) => {
    if (!acc[task.category]) {
      acc[task.category] = [];
    }
    // 添加一个taskId字段以匹配组件预期的类型
    const adaptedTask = {
      ...task,
      taskId: task.id
    };
    acc[task.category].push(adaptedTask);
    return acc;
  }, {});
};

// 将ExecutionRecord适配为组件期望的格式
const adaptRecordToComponentFormat = (records: ExecutionRecord[]): Record<string, ComponentExecutionRecord[]> => {
  return records.reduce((acc: { [key: string]: ComponentExecutionRecord[] }, record: ExecutionRecord) => {
    if (!acc[record.category]) {
      acc[record.category] = [];
    }
    // 转换为组件期望的类型
    const adaptedRecord = {
      ...record,
      logs: record.logs || [],
    } as ComponentExecutionRecord;
    
    acc[record.category].push(adaptedRecord);
    return acc;
  }, {});
};

export const HomeDashboard = () => {
  // 使用新的上下文
  const { tasks, addTask } = useTaskContext();
  const { executionRecords } = useTaskHistoryContext();

  // 使用适配器转换数据
  const adaptedTemplatesByCategory = adaptTaskToComponentFormat(tasks);
  const adaptedHistoryByCategory = adaptRecordToComponentFormat(executionRecords);

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900">
      <div className="max-w-[1200px] mx-auto p-6">
        <h1 className="text-2xl font-bold mb-8 dark:text-white">浏览器自动化任务管理器</h1>
        
        <TaskExecution 
          tasksByCategory={adaptedTemplatesByCategory}
          addTaskToContext={addTask}
        />
        
        <TaskHistory tasksByCategory={adaptedHistoryByCategory} />
      </div>
    </div>
  );
};